package com.xinshujia.adapter;

import com.google.gson.*;

import java.lang.reflect.Type;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

/**
 * ************************************
 * *   @author: 野狼上校               **
 * *   @since: 2024-07-11 10:26       **
 * *   @version: 1.0                  **
 * *************************************
 * <p>
 * 日期适配器  匹配的格式: yyyy-MM-dd
 */

public class DateAdapter implements JsonDeserializer<Date>, JsonSerializer<Date> {
    private static final SimpleDateFormat formatPattern = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public Date deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
        try {
            formatPattern.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
            return formatPattern.parse(jsonElement.getAsString());
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public JsonElement serialize(Date date, Type type, JsonSerializationContext jsonSerializationContext) {
        formatPattern.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
        return new JsonPrimitive(formatPattern.format(date));
    }
}
